﻿namespace EyeOpen.Windows.Serialize
{
	using System;
	using System.ComponentModel;
	using System.Drawing;
	using System.IO;
	using System.Windows.Forms;
	using EyeOpen.Windows.Form;
	using EyeOpen.Windows.Form.Serialize;
	using Container = EyeOpen.Container;
	using IContainer = EyeOpen.IContainer;

	public class ControlSerializerDialog
	{
		private const string FileNameFilter = "Form serializer file|*.bin";

		private readonly XmlFormSerializer xmlFormSerializer;

		private readonly Control control;
		private string fileName;

		public ControlSerializerDialog(Control control, string fileName)
		{
			this.control = control;
			this.fileName = fileName;

			xmlFormSerializer = new XmlFormSerializer(InitContainer());

			if (File.Exists(fileName))
			{
				xmlFormSerializer.Load(control, fileName);
			}
		}

		public void Load()
		{
			if (fileName == null)
			{
				var openFileDialog =
					new OpenFileDialog
						{
							Filter = FileNameFilter,
							CheckFileExists = true,
							Multiselect = false
						};

				openFileDialog.FileOk += LoadFileOk;
				openFileDialog.ShowDialog();
			}
			else
			{
				xmlFormSerializer.Save(control, fileName);
			}
		}

		public void Save()
		{
			if (fileName == null)
			{
				var saveFileDialog =
					new SaveFileDialog
						{
							Filter = FileNameFilter
						};

				saveFileDialog.FileOk += SaveFileOk;
				saveFileDialog.ShowDialog();
			}
			else
			{
				xmlFormSerializer.Save(control, fileName);
			}
		}

		private IContainer InitContainer()
		{
			var container = new Container();

			RegisterDefaultTypeConverters(container);
			RegisterDefaulControlConverters(container);

			return container;
		}

		private void RegisterDefaulControlConverters(Container container)
		{
			container.Register<TextBox>(new TextBoxControlSerializer(container));
			container.Register<CheckBox>(new CheckBoxControlSerializer(container));
		}

		private void RegisterDefaultTypeConverters(IContainer container)
		{
			container.Register<string>(new StringConverter());
			container.Register<bool>(new BooleanConverter());
			container.Register<Font>(new FontConverter());
		}

		private void SaveFileOk(object sender, System.ComponentModel.CancelEventArgs e)
		{
			fileName = ((SaveFileDialog)sender).FileName;
			xmlFormSerializer.Save(control, fileName);
		}

		private void LoadFileOk(object sender, System.ComponentModel.CancelEventArgs e)
		{
			fileName = ((OpenFileDialog)sender).FileName;
			xmlFormSerializer.Load(control, fileName);
		}
	}
}